import React, { Component } from "react";
import styles from './uc-input.module.css'
import propTypes from 'prop-types'

export default class UcInput extends Component {
    static defaultProps = {
        type: 'text', //类型
        model: 'null', // 非受控
        multi: false, // 多行 
        label: '', //描述
        style: {} // 外部样式
    }

    static propTypes = {
        type: propTypes.string,
        model: propTypes.shape({
            name: propTypes.string.isRequired,
            value: propTypes.string.isRequired,
            onChange: propTypes.func.isRequired,
        }),
        multi: propTypes.bool,
        label: propTypes.string,
        style: propTypes.object
    }

    renderLabel = () => {
        let { label } = this.props;
        return label ? <span>{label}</span> : null;
    }

    renderInput = () => {
        let { model, style, label, type } = this.props
        let el = null;

        // 非受控
        if (!model) {
            el = (
                <div className={styles.ucInput}>
                    <input
                        type={type}
                        defaultValue=""
                        style={{
                            paddingLeft: label ? '1.44rem' : '0.24rem',
                            ...style
                        }}
                    />
                    {this.renderLabel()}
                </div>
            );

            return el;
        }

        //受控
        let { name, value, onChange } = model
        el = (
            <div className={styles.ucInput}>
                <input
                    type={type}
                    value={value}
                    name={name}
                    onChange={onChange}

                    style={{
                        paddingLeft: label ? '1.44rem' : '0.24rem',
                        ...style
                    }}
                />
                {this.renderLabel()}
            </div>
        )
        return el;
    }

    renderTextArea = () => {
        let { model } = this.props;
        let el = null;
        // 非受控多行
        if (!model) {
            el = (
                <div>
                    {this.renderLabel()}
                    <textarea></textarea>
                </div>
            );
            return el;
        }

        // 受控多行
        let { name, value, onChange } = model;

        el = (
            <div>
                {this.renderLabel()}
                <textarea value={value} name={name} onChange={onChange}></textarea>
            </div>
        );

        return el;
    }

    render() {
        let { multi } = this.props;
        return multi ? this.renderTextArea() : this.renderInput();
    }
}